<!--素材管理-->
<template>
  <div id="thirdWechatMaterialLibrary" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item v-if="mode==='editor'">
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" />
        </el-form-item>
        <el-form-item>
          <el-select v-model="listQuery.categoryId" placeholder="请选择素材分类" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.keyword" placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-tabs v-if="mode==='editor'" v-model="activeName" class="common-tabs">
      <el-tab-pane name="text">
        <span slot="label"><i class="el-icon-notebook-2" /> 文本</span>
      </el-tab-pane>
      <el-tab-pane name="image">
        <span slot="label"><i class="el-icon-picture" /> 图片</span>
      </el-tab-pane>
      <el-tab-pane name="audio">
        <span slot="label"><i class="el-icon-microphone" /> 语音</span>
      </el-tab-pane>
      <el-tab-pane name="video">
        <span slot="label"><i class="el-icon-video-play" /> 视频</span>
      </el-tab-pane>
    </el-tabs>
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar :remove="activeName!=='image' && mode==='editor'" @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <template v-if="activeName==='image'">
        <div class="common-flow-container">
          <div
            v-for="item in list"
            :key="item.id"
            class="flow-item tc">
            <el-image
              :src="common.getFileView(item.photo)"
              style="border-radius: 4px;height: 120px; width: 100%;"
              :preview-src-list="[common.getFileView(item.photo)]">
              <div slot="placeholder" class="image-slot">
                加载中<span class="dot">...</span>
              </div>
            </el-image>
            <div style="font-size: 15px;font-weight: bold;height: 44px;">{{ item.title }}</div>
            <div style="padding-bottom:15px">
              <button-option v-if="mode==='editor'" style="font-size: 18px;" icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(item)" />
              <el-button v-if="mode==='select'" style="margin-top: 10px;" type="primary" @click="handleSelect(item)">选择<i class="el-icon-circle-check  el-icon--right" /></el-button>
            </div>
          </div>
        </div>
      </template>
      <el-table
        v-else
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <template v-if="activeName==='video'|| activeName==='audio'">
          <el-table-column label="MediaId" prop="mediaId" width="440" show-overflow-tooltip />
          <el-table-column label="名称" prop="title" width="240" show-overflow-tooltip />
        </template>
        <el-table-column label="描述" prop="summary" min-width="200" show-overflow-tooltip />
        <el-table-column prop="gmtModified" sortable label="修改时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="90">
          <template slot-scope="scope">
            <template v-if="mode==='editor'">
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            </template>
            <template v-if="mode==='select'">
              <button-option icon="el-icon-circle-check" skin="primary" title="选择" @click="handleSelect(scope.row)" />
            </template>
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="thirdWechatArticleRules"
          :model="thirdWechatArticleRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="所属分类:" prop="categoryId">
            <el-select-tree v-model="thirdWechatArticleRecord.categoryId" :data="categories" :props="{children: 'children', label: 'name'}" />
          </el-form-item>

          <template v-if="activeName==='text'">
            <el-form-item label="内容:" prop="content">
              <el-input
                v-model="thirdWechatArticleRecord.content"
                :rows="4"
                type="textarea"
                maxlength="300"
                show-word-limit
                placeholder="请输入内容" />
            </el-form-item>
          </template>
          <template v-if="activeName==='image'">
            <el-form-item>
              <el-upload
                action=""
                :show-file-list="false"
                :auto-upload="false"
                accept="image/png,image/jpeg,image/jpg"
                :on-change="handleUploadChange">
                <el-button type="primary">选择图片</el-button>
                <div slot="tip" class="common-tips m-b-10">格式支持png/jpg/jpeg格式，大小不超过10M</div>
              </el-upload>
            </el-form-item>
            <el-form-item v-if="thirdWechatArticleRecord.fileName">
              您已选择：{{ thirdWechatArticleRecord.fileName }}
            </el-form-item>
            <el-form-item label="标题:" prop="title">
              <el-input v-model="thirdWechatArticleRecord.title" maxlength="30" show-word-limit placeholder="标题将展示在相关展示页面，建议填写清晰、准确、生动的标题" />
            </el-form-item>
          </template>
          <template v-if="activeName==='video'|| activeName==='audio'">
            <el-form-item>
              <template v-if="activeName==='audio'">
                <el-upload
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  accept=" audio/mpeg"
                  :on-change="handleUploadChange">
                  <el-button type="primary">选择语音</el-button>
                  <div slot="tip" class="common-tips m-b-10">格式支持mp3/wma/wav/amr格式，大小不超过2M且播放长度不能超过60s</div>

                </el-upload>
              </template>
              <template v-if="activeName==='video'">
                <el-upload
                  action=""
                  :show-file-list="false"
                  :auto-upload="false"
                  accept="audio/mp4, video/mp4"
                  :on-change="handleUploadChange">
                  <el-button type="primary">选择视频</el-button>
                  <div slot="tip" class="common-tips m-b-10">格式支持MP4格式，大小不超过10M</div>

                </el-upload>
              </template>

            </el-form-item>
            <el-form-item v-if="thirdWechatArticleRecord.fileName">
              您已选择：{{ thirdWechatArticleRecord.fileName }}
            </el-form-item>
            <el-form-item label="标题:" prop="title">
              <el-input v-model="thirdWechatArticleRecord.title" maxlength="30" show-word-limit placeholder="标题将展示在相关播放页面，建议填写清晰、准确、生动的标题" />
            </el-form-item>
            <el-form-item label="描述:" prop="content">
              <el-input
                v-model="thirdWechatArticleRecord.content"
                :rows="4"
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="标题将展示在相关播放页面，建议填写简洁明确，有信息量的内容" />
            </el-form-item>
          </template>

        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
import applicationKeySelect from '../applicationKeySelect'
export default {
  components: { applicationKeySelect },
  props: {
    mode: {
      type: String,
      default: 'editor'
    },
    type: {
      type: String,
      default: 'text'
    },
    appId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      activeName: 'text',
      categories: [],
      list: [],
      total: 0,
      listQuery: {
        appId: '',
        type: 1,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT,
        resourceType: 3,
        categoryId: ''
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      thirdWechatArticleRecord: {},
      thirdWechatArticleFrom: new FormData(),
      thirdWechatArticleRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入描述', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择所属分类', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    type: function(value) {
      this.activeName = value
    },
    appId: function(value) {
      this.listQuery = {
        ...this.listQuery,
        appId: value
      }
    },
    activeName: function(val) {
      this.sideBox.recordShow = false
      var resourceType = 0
      if (val === 'text') {
        resourceType = 3
      }
      if (val === 'image') {
        resourceType = 0
      }
      if (val === 'audio') {
        resourceType = 1
      }
      if (val === 'video') {
        resourceType = 2
      }
      this.listQuery = {
        ...this.listQuery,
        resourceType: resourceType,
        categoryId: ''
      }
      if (this.listQuery.appId) {
        this.handleFilter()
        this.fetchCategories()
      }
    },
    'listQuery.appId': function(val) {
      this.fetchData()
      this.fetchCategories()
    }
  },
  created() {
    this.activeName = this.type
    if (this.appId) {
      this.listQuery = {
        ...this.listQuery,
        appId: this.appId
      }
    }
  },
  methods: {
    async fetchCategories() {
      var res = await this.$store.dispatch('thirdWechatResourceCategoryTree', { appId: this.listQuery.appId, type: this.listQuery.resourceType })
      this.categories = res
    },
    // 选择文件
    handleUploadChange(file) {
      var sizeLimit = 10
      console.log(file.raw.type)
      console.log(file)
      var ext = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (this.activeName === 'image') {
        sizeLimit = 10
        if (!'png,jpg,jpeg'.includes(ext)) {
          this.$modal.msgWarning('请选择图片文件!')
          return
        }
      } else if (this.activeName === 'audio') {
        sizeLimit = 2
        if (!'mp3,wma,wav,amr'.includes(ext)) {
          this.$modal.msgWarning('请选择mp3/wma/wav/amr格式的音频文件!')
          return
        }
      } else if (this.activeName === 'video') {
        sizeLimit = 10
        if (!'mp4'.includes(ext)) {
          this.$modal.msgWarning('请选择mp3/wma/wav/amr格式的音频文件!')
          return
        }
      }
      const isLt = file.size / 1024 / 1024 < sizeLimit
      if (!isLt) {
        this.$modal.msgWarning(`文件大小不能超过${sizeLimit}MB!`)
        return
      }
      this.thirdWechatArticleFrom = new FormData()
      this.thirdWechatArticleFrom.append('file', file.raw)
      this.thirdWechatArticleRecord = {
        ...this.thirdWechatArticleRecord,
        fileName: file.name,
        title: this.thirdWechatArticleRecord.title ? this.thirdWechatArticleRecord.title : file.name
      }
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        categoryId: '',
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('thirdWechatArticlePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.thirdWechatArticleRecord = {
        resourceType: this.listQuery.resourceType,
        appId: this.listQuery.appId,
        title: this.listQuery.resourceType === 3 ? '-' : '',
        catalogId: this.constants.FILE_CATALOG_WECHAT_ARTICLE_CONTENT
      }

      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增素材'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        if (this.categories.length > 0) {
          this.thirdWechatArticleRecord = {
            ...this.thirdWechatArticleRecord,
            categoryId: this.categories[0].id
          }
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          for (var item in this.thirdWechatArticleRecord) {
            this.thirdWechatArticleFrom.delete(item)
            this.thirdWechatArticleFrom.append(item, this.thirdWechatArticleRecord[item])
          }
          this.$store.dispatch('thirdWechatArticleSaveBasic', this.thirdWechatArticleFrom).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.thirdWechatArticleRecord = Object.assign({}, row) // copy obj
      this.thirdWechatArticleRecord = {
        ...this.thirdWechatArticleRecord,
        catalogId: this.constants.FILE_CATALOG_WECHAT_ARTICLE_CONTENT,
        content: this.thirdWechatArticleRecord.summary
      }
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑素材'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatArticleRecord)
          this.$store.dispatch('thirdWechatArticleUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      console.log(this.listQuery)
      if (this.listQuery.resourceType !== 0) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }

      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('thirdWechatArticleRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleSelect(row) {
      this.$emit('select', row)
    }

  }
}
</script>
<style lang="scss" scope >

</style>
